package com.wyw.core.config.support;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.wyw.core.config.XmlConfigParse;
import com.wyw.core.secu.dto.Menu;
import com.wyw.core.secu.dto.XmlConfigType;
import com.wyw.core.util.CacheManager;

public class SecurityRoleMenueParse implements XmlConfigParse{

	@Override
	public void parse(XmlConfigType xmlConfigType, Document xmlConfig) throws Exception {
		// TODO Auto-generated method stub
		Element rootElement =xmlConfig.getRootElement();
		Menu menu = psrseConfigToMenu(rootElement.getChild("menu"));
		if(menu !=null){
			net.sf.ehcache.Element config=new  net.sf.ehcache.Element(CacheManager.security_role_menue_list,menu);
			CacheManager.put(config);
		}
	}
	
	private Menu psrseConfigToMenu(Element element){
		Element roleListConfigElement=element.getChild("roleList");
		Element submenusConfigElement=element.getChild("subMenus");
		List subMenusList =null;
		List roleList =null ;
		
		if(roleListConfigElement == null && submenusConfigElement == null){//角色为空，且子菜单也为空
			return null;
		}
		
		if(roleListConfigElement != null ){
			roleList = parseRoleList(roleListConfigElement);
		}
		
		if( submenusConfigElement !=null){//角色为空，且子菜单不为空
			subMenusList = parseSubMenuList( submenusConfigElement);
		}
		
		if(roleList !=null || subMenusList !=null){
			Menu newMenu = getNewMenu(element);
			newMenu.setSubmenus(subMenusList);
			newMenu.setRoleList(roleList);
			return newMenu;
		}
		
		return null; 
	}
	
	private List parseRoleList(Element roleListConfigElement){
		List roleList = new ArrayList();
		List<Element> roleElementConfigList=roleListConfigElement.getChildren("role");
		String role;
		for(Element element : roleElementConfigList){
			role=element.getText();// element.getChild("role");
			//System.out.println("role:"+role);
			if(!StringUtils.isEmpty(role)){
				roleList.add(role);
			}
		}
		return roleList.size()>0?roleList:null;
	}
	
	private List parseSubMenuList(Element submenusConfigElement){
		List subMenusList = new ArrayList();
		List<Element> subMenusConfigElementList = submenusConfigElement.getChildren("menu");
		Menu menuSB;
		for(Element elementSB:subMenusConfigElementList){
			menuSB=psrseConfigToMenu(elementSB);
			if(menuSB !=null){
				subMenusList.add(menuSB);
			}
		}
		return subMenusList.size()>0?subMenusList:null;
	}
	
	private Menu getNewMenu(Element element){
		Menu menu = new Menu();
		menu.setId(element.getAttributeValue("id"));
		menu.setName(element.getChildText("name"));
		menu.setDesc(element.getChildText("desc"));
		menu.setAction(element.getChildText("action"));
		return menu;
	}
		
}
